package com.flyu.myReflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestReflect5 {
    // 普通方式调用
    public static void test01(){
         long startTime = System.currentTimeMillis();

        User user = new User();

        for (int i = 0; i < 1000000; i++) {
            user.getName();
        }

        long endTime = System.currentTimeMillis();

        System.out.println("普通方式调用10亿次："+(endTime-startTime)+"ms");

    }
    // 反射方式调用
    public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        Class c1 = user.getClass();
        long startTime = System.currentTimeMillis();
        // 获取方法
        Method getName = c1.getDeclaredMethod("getName");

        for (int i = 0; i < 1000000; i++) {
            getName.invoke(user);
        }

        long endTime = System.currentTimeMillis();

        System.out.println("反射方式调用10亿次："+(endTime-startTime)+"ms");

    }
    // 反射方式调用 关闭检测
    public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        Class c1 = user.getClass();

        long startTime = System.currentTimeMillis();
        // 获取方法
        Method getName = c1.getDeclaredMethod("getName");
        getName.setAccessible(true);

        for (int i = 0; i < 1000000; i++) {
            getName.invoke(user);
        }

        long endTime = System.currentTimeMillis();

        System.out.println("反射并关闭检测方式调用10亿次："+(endTime-startTime)+"ms");

    }

    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        test01();
        test02();
        test03();
    }
}
